let lastPageYOffset = 0;
let lastScrollBehavior = 'auto';

export function $(el) {
    return document.querySelector(el);
}

/**
 * 在垂直方向锁定页面滚动
 **/
export function lockPageYScroll() {
    const doc = document.documentElement;
    lastPageYOffset =
        window.pageYOffset || doc.scrollTop || document.body.scrollTop;
    lastScrollBehavior = doc.style.scrollBehavior;
    doc.style.cssText = `height:100%;overflow:hidden;position:relative;`;
}

/**
 * 在垂直方向释放页面滚动的锁定
 **/
export function unlockPageYScroll() {
    const doc = document.documentElement;
    doc.style.cssText = `height:auto;overflow:auto;`;
    doc.scrollTop = lastPageYOffset || 0;
}

/**
 * 当回退时刷新页面
 * performance.navigation.type 已被废弃，但在旧浏览器中可用
 * type 含义：0普通导航 1刷新 2后退 255其他
 * @link https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation/type
 *
 * e.persisted 在某些旧浏览器中始终返回 false，因为代码实现有问题。具体解析参考
 * @link https://stackoverflow.com/questions/17432899/javascript-bfcache-pageshow-event-event-persisted-always-set-to-false
 *
 * @param {() => {}} callback 回调函数
 */
export function enableReloadWhenPageback(callback) {
    window.addEventListener(
        'pageshow',
        (e) => {
            if (
                e.persisted ||
                (window.performance &&
                    window.performance.navigation &&
                    window.performance.navigation.type === 2)
            ) {
                if (callback && typeof callback === 'function') {
                    callback();
                }
                location.reload();
            }
        },
        false
    );
}
